/**
 * 重点问题分析管理器 - 负责重点问题分析页面的交互功能
 * 包含问题筛选、统计分析、趋势分析、重复问题识别等功能
 */
class KeyIssuesManager {
    constructor() {
        this.filters = {
            region: '',
            district: '',
            issueType: '',
            timeRange: 'month',
            severity: '',
            keyword: ''
        };
        this.pagination = {
            page: 1,
            pageSize: 10,
            total: 0
        };
        this.charts = {};
        this.issues = [];
        this.selectedIssues = new Set();
        this.sortBy = 'severity';
        this.sortOrder = 'desc';
        
        this.init();
    }

    /**
     * 初始化重点问题分析管理器
     */
    init() {
        this.loadKeyIssues();
        this.initializeCharts();
        this.bindEvents();
        this.loadStatistics();
    }

    /**
     * 绑定事件处理
     */
    bindEvents() {
        // 筛选器事件
        document.getElementById('regionFilter')?.addEventListener('change', (e) => {
            this.filters.region = e.target.value;
            this.updateDistrictOptions(e.target.value);
            this.applyFilters();
        });

        document.getElementById('districtFilter')?.addEventListener('change', (e) => {
            this.filters.district = e.target.value;
            this.applyFilters();
        });

        document.getElementById('issueTypeFilter')?.addEventListener('change', (e) => {
            this.filters.issueType = e.target.value;
            this.applyFilters();
        });

        document.getElementById('timeRangeFilter')?.addEventListener('change', (e) => {
            this.filters.timeRange = e.target.value;
            this.applyFilters();
        });

        document.getElementById('severityFilter')?.addEventListener('change', (e) => {
            this.filters.severity = e.target.value;
            this.applyFilters();
        });

        // 搜索事件
        const searchInput = document.getElementById('searchInput');
        let searchTimeout;
        searchInput?.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                this.filters.keyword = e.target.value;
                this.applyFilters();
            }, 500);
        });

        // 按钮事件
        document.getElementById('searchBtn')?.addEventListener('click', () => {
            this.applyFilters();
        });

        document.getElementById('resetBtn')?.addEventListener('click', () => {
            this.resetFilters();
        });

        document.getElementById('exportBtn')?.addEventListener('click', () => {
            this.exportKeyIssues();
        });

        // 排序事件
        document.getElementById('sortBy')?.addEventListener('change', (e) => {
            this.sortBy = e.target.value;
            this.applyFilters();
        });

        // 分页事件
        document.getElementById('prevPage')?.addEventListener('click', () => {
            if (this.pagination.page > 1) {
                this.pagination.page--;
                this.loadKeyIssues();
            }
        });

        document.getElementById('nextPage')?.addEventListener('click', () => {
            if (this.pagination.page < this.getTotalPages()) {
                this.pagination.page++;
                this.loadKeyIssues();
            }
        });

        // 批量操作事件
        document.getElementById('selectAll')?.addEventListener('change', (e) => {
            this.toggleSelectAll(e.target.checked);
        });

        document.getElementById('batchAnalyze')?.addEventListener('click', () => {
            this.batchAnalyzeIssues();
        });

        document.getElementById('batchExport')?.addEventListener('click', () => {
            this.batchExportIssues();
        });

        // 问题项点击事件（事件委托）
        document.getElementById('issuesList')?.addEventListener('click', (e) => {
            const issueRow = e.target.closest('.issue-row');
            if (!issueRow) return;

            // 查看详情
            if (e.target.closest('.view-btn')) {
                e.preventDefault();
                this.viewIssueDetail(issueRow.dataset.issueId);
            }

            // 分析问题
            if (e.target.closest('.analyze-btn')) {
                e.preventDefault();
                this.analyzeIssue(issueRow.dataset.issueId);
            }

            // 选择问题
            if (e.target.closest('.issue-checkbox')) {
                this.toggleIssueSelection(issueRow.dataset.issueId, e.target.checked);
            }
        });
    }

    /**
     * 加载重点问题数据
     */
    async loadKeyIssues() {
        try {
            const params = new URLSearchParams({
                page: this.pagination.page,
                page_size: this.pagination.pageSize,
                ...this.filters,
                sort_by: this.sortBy,
                sort_order: this.sortOrder
            });

            const response = await fetch(`/api/key-issues/issues?${params}`);
            const result = await response.json();

            if (result.code === 200) {
                this.issues = result.data.issues;
                this.pagination.total = result.data.total;
                this.renderIssuesList();
                this.updatePagination();
            } else {
                this.showNotification('加载重点问题失败', 'error');
            }
        } catch (error) {
            console.error('加载重点问题出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 渲染问题列表
     */
    renderIssuesList() {
        const container = document.getElementById('issuesList');
        if (!container) return;

        if (this.issues.length === 0) {
            container.innerHTML = `
                <div class="text-center py-12 text-slate-500">
                    <i class="fas fa-inbox text-4xl mb-4"></i>
                    <p>暂无重点问题数据</p>
                </div>
            `;
            return;
        }

        const html = this.issues.map(issue => `
            <tr class="issue-row hover:bg-slate-50" data-issue-id="${issue.id}">
                <td class="p-4">
                    <input type="checkbox" class="issue-checkbox rounded" 
                           ${this.selectedIssues.has(issue.id) ? 'checked' : ''}>
                </td>
                <td class="p-4">
                    <span class="font-medium text-indigo-600">${issue.issue_code}</span>
                </td>
                <td class="p-4">
                    <div class="max-w-xs">
                        <p class="text-sm text-slate-800 font-medium">${issue.title}</p>
                        <p class="text-xs text-slate-500 mt-1">${issue.description}</p>
                    </div>
                </td>
                <td class="p-4">
                    <span class="text-sm text-slate-600">${issue.region}</span>
                    <span class="text-xs text-slate-500 block">${issue.district}</span>
                </td>
                <td class="p-4">
                    <div class="flex items-center space-x-2">
                        <span class="text-lg font-semibold ${this.getFrequencyColor(issue.frequency)}">${issue.frequency}</span>
                        ${issue.trend > 0 ? 
                            `<span class="text-xs text-red-600">+${issue.trend}</span>` : 
                            `<span class="text-xs text-green-600">${issue.trend}</span>`
                        }
                    </div>
                </td>
                <td class="p-4">
                    ${this.getSeverityBadge(issue.severity)}
                </td>
                <td class="p-4">
                    ${this.getStatusBadge(issue.status)}
                </td>
                <td class="p-4">
                    <button class="view-btn text-indigo-600 hover:text-indigo-800 text-sm mr-2">
                        <i class="fas fa-eye mr-1"></i>查看
                    </button>
                    <button class="analyze-btn text-green-600 hover:text-green-800 text-sm">
                        <i class="fas fa-chart-line mr-1"></i>分析
                    </button>
                </td>
            </tr>
        `).join('');

        container.innerHTML = html;
    }

    /**
     * 获取频次颜色
     */
    getFrequencyColor(frequency) {
        if (frequency >= 50) return 'text-red-600';
        if (frequency >= 30) return 'text-orange-600';
        if (frequency >= 10) return 'text-yellow-600';
        return 'text-green-600';
    }

    /**
     * 获取严重程度标签
     */
    getSeverityBadge(severity) {
        const badges = {
            '紧急': '<span class="px-2 py-1 bg-red-100 text-red-700 text-xs rounded-full">紧急</span>',
            '重要': '<span class="px-2 py-1 bg-yellow-100 text-yellow-700 text-xs rounded-full">重要</span>',
            '一般': '<span class="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full">一般</span>'
        };
        return badges[severity] || badges['一般'];
    }

    /**
     * 获取状态标签
     */
    getStatusBadge(status) {
        const badges = {
            'pending': '<span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">待处理</span>',
            'processing': '<span class="px-2 py-1 bg-yellow-100 text-yellow-700 text-xs rounded-full">处理中</span>',
            'resolved': '<span class="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full">已处理</span>',
            'investigating': '<span class="px-2 py-1 bg-purple-100 text-purple-700 text-xs rounded-full">调查中</span>'
        };
        return badges[status] || badges['pending'];
    }

    /**
     * 更新分页显示
     */
    updatePagination() {
        const totalPages = this.getTotalPages();
        
        // 更新页码显示
        document.getElementById('currentPage')?.replaceWith(
            `<span id="currentPage">${this.pagination.page}</span>`
        );
        
        document.getElementById('totalPages')?.replaceWith(
            `<span id="totalPages">${totalPages}</span>`
        );

        // 更新按钮状态
        const prevBtn = document.getElementById('prevPage');
        const nextBtn = document.getElementById('nextPage');
        
        if (prevBtn) {
            prevBtn.disabled = this.pagination.page <= 1;
            prevBtn.classList.toggle('opacity-50', this.pagination.page <= 1);
        }
        
        if (nextBtn) {
            nextBtn.disabled = this.pagination.page >= totalPages;
            nextBtn.classList.toggle('opacity-50', this.pagination.page >= totalPages);
        }

        // 更新全选框状态
        const selectAll = document.getElementById('selectAll');
        if (selectAll) {
            const allSelected = this.issues.length > 0 && 
                this.issues.every(issue => this.selectedIssues.has(issue.id));
            selectAll.checked = allSelected;
        }
    }

    /**
     * 获取总页数
     */
    getTotalPages() {
        return Math.ceil(this.pagination.total / this.pagination.pageSize);
    }

    /**
     * 初始化图表
     */
    initializeCharts() {
        this.initIssueTypeChart();
        this.initRegionChart();
        this.initTrendChart();
    }

    /**
     * 初始化问题类型分布图
     */
    initIssueTypeChart() {
        const ctx = document.getElementById('issueTypeChart');
        if (!ctx) return;

        this.charts.issueType = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['环境污染', '噪音扰民', '市容管理', '交通问题', '设施维护'],
                datasets: [{
                    data: [30, 25, 20, 15, 10],
                    backgroundColor: [
                        'rgba(239, 68, 68, 0.8)',
                        'rgba(245, 158, 11, 0.8)',
                        'rgba(59, 130, 246, 0.8)',
                        'rgba(16, 185, 129, 0.8)',
                        'rgba(139, 92, 246, 0.8)'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right',
                        labels: {
                            padding: 15,
                            font: {
                                size: 12
                            }
                        }
                    }
                }
            }
        });
    }

    /**
     * 初始化区域问题分布图
     */
    initRegionChart() {
        const ctx = document.getElementById('regionIssueChart');
        if (!ctx) return;

        this.charts.regionIssue = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['南山区', '福田区', '宝安区', '罗湖区', '龙岗区'],
                datasets: [{
                    label: '问题数量',
                    data: [45, 38, 32, 28, 22],
                    backgroundColor: 'rgba(59, 130, 246, 0.8)',
                    borderRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

    /**
     * 初始化趋势图
     */
    initTrendChart() {
        const ctx = document.getElementById('trendChart');
        if (!ctx) return;

        this.charts.trend = new Chart(ctx, {
            type: 'line',
            data: {
                labels: this.getLast30Days(),
                datasets: [{
                    label: '问题数量',
                    data: this.generateTrendData(),
                    borderColor: 'rgb(239, 68, 68)',
                    backgroundColor: 'rgba(239, 68, 68, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

    /**
     * 获取最近30天的日期
     */
    getLast30Days() {
        const days = [];
        for (let i = 29; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            days.push(date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }));
        }
        return days;
    }

    /**
     * 生成趋势数据
     */
    generateTrendData() {
        const data = [];
        for (let i = 0; i < 30; i++) {
            data.push(Math.floor(Math.random() * 20) + 10);
        }
        return data;
    }

    /**
     * 加载统计数据
     */
    async loadStatistics() {
        try {
            const response = await fetch('/api/key-issues/statistics');
            const result = await response.json();

            if (result.code === 200) {
                this.updateStatistics(result.data);
            }
        } catch (error) {
            console.error('加载统计数据出错:', error);
        }
    }

    /**
     * 更新统计数据显示
     */
    updateStatistics(stats) {
        // 更新紧急问题
        this.updateNumber('urgentIssues', stats.urgent || 0);
        this.updateNumber('urgentIssuesChange', stats.urgentChange || 0, true);

        // 更新重要问题
        this.updateNumber('importantIssues', stats.important || 0);
        this.updateNumber('importantIssuesChange', stats.importantChange || 0, true);

        // 更新重复问题
        this.updateNumber('repeatedIssues', stats.repeated || 0);
        this.updateNumber('repeatRate', stats.repeatRate || 0, false, '%');
    }

    /**
     * 更新数字显示
     */
    updateNumber(elementId, value, showChange = false, suffix = '') {
        const element = document.getElementById(elementId);
        if (!element) return;

        if (showChange) {
            const isPositive = value > 0;
            const changeClass = isPositive ? 'text-red-600' : 'text-green-600';
            const changeSymbol = isPositive ? '+' : '';
            element.innerHTML = `<span class="${changeClass}">${changeSymbol}${value}${suffix}</span>`;
        } else {
            element.textContent = value + suffix;
        }
    }

    /**
     * 应用筛选器
     */
    applyFilters() {
        this.pagination.page = 1;
        this.selectedIssues.clear();
        this.loadKeyIssues();
        this.loadStatistics();
    }

    /**
     * 重置筛选器
     */
    resetFilters() {
        this.filters = {
            region: '',
            district: '',
            issueType: '',
            timeRange: 'month',
            severity: '',
            keyword: ''
        };
        this.pagination.page = 1;
        this.selectedIssues.clear();

        // 重置表单
        document.getElementById('regionFilter').value = '';
        document.getElementById('districtFilter').value = '';
        document.getElementById('issueTypeFilter').value = '';
        document.getElementById('timeRangeFilter').value = 'month';
        document.getElementById('severityFilter').value = '';
        document.getElementById('searchInput').value = '';

        this.loadKeyIssues();
        this.loadStatistics();
    }

    /**
     * 更新区域选项
     */
    updateDistrictOptions(region) {
        const districtSelect = document.getElementById('districtFilter');
        if (!districtSelect) return;

        const districtOptions = {
            '南山区': ['科技园片区', '南头片区', '西丽片区'],
            '福田区': ['华强北片区', '中心区片区', '福田口岸片区'],
            '罗湖区': ['东门片区', '罗湖口岸片区', '莲塘片区'],
            '宝安区': ['新安片区', '西乡片区', '福永片区'],
            '龙岗区': ['龙岗中心城片区', '坂田片区', '布吉片区']
        };

        const districts = districtOptions[region] || ['全部街道'];
        
        districtSelect.innerHTML = districts.map(district => 
            `<option value="${district === '全部街道' ? '' : district}">${district}</option>`
        ).join('');
    }

    /**
     * 切换全选
     */
    toggleSelectAll(checked) {
        this.issues.forEach(issue => {
            if (checked) {
                this.selectedIssues.add(issue.id);
            } else {
                this.selectedIssues.delete(issue.id);
            }
        });
        this.renderIssuesList();
    }

    /**
     * 切换单个问题选择
     */
    toggleIssueSelection(issueId, checked) {
        if (checked) {
            this.selectedIssues.add(issueId);
        } else {
            this.selectedIssues.delete(issueId);
        }
    }

    /**
     * 查看问题详情
     */
    viewIssueDetail(issueId) {
        const issue = this.issues.find(i => i.id === issueId);
        if (!issue) return;

        const modalHtml = `
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="issueDetailModal">
                <div class="bg-white rounded-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">问题详情</h3>
                        <button class="text-gray-500 hover:text-gray-700" onclick="keyIssuesManager.closeModal('issueDetailModal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">问题编号</label>
                            <p class="text-sm text-gray-900">${issue.issue_code}</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">问题描述</label>
                            <p class="text-sm text-gray-900">${issue.title}</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">详细描述</label>
                            <p class="text-sm text-gray-900">${issue.description}</p>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">涉及区域</label>
                                <p class="text-sm text-gray-900">${issue.region} - ${issue.district}</p>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">严重程度</label>
                                ${this.getSeverityBadge(issue.severity)}
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">发生频次</label>
                                <p class="text-sm text-gray-900">${issue.frequency} 次</p>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">处理状态</label>
                                ${this.getStatusBadge(issue.status)}
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">相关信访件</label>
                            <div class="space-y-2">
                                ${this.generateRelatedPetitions(issue.related_petitions || [])}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
    }

    /**
     * 生成相关信访件列表
     */
    generateRelatedPetitions(petitions) {
        if (petitions.length === 0) {
            return '<p class="text-sm text-gray-500">暂无相关信访件</p>';
        }

        return petitions.map(petition => `
            <div class="flex items-center justify-between p-2 bg-gray-50 rounded">
                <div>
                    <p class="text-sm font-medium">${petition.title}</p>
                    <p class="text-xs text-gray-500">${petition.date}</p>
                </div>
                <button class="text-blue-600 hover:text-blue-800 text-sm">查看</button>
            </div>
        `).join('');
    }

    /**
     * 分析问题
     */
    async analyzeIssue(issueId) {
        try {
            const response = await fetch(`/api/key-issues/${issueId}/analyze`, {
                method: 'POST'
            });
            
            const result = await response.json();
            
            if (result.code === 200) {
                this.showAnalysisResult(result.data);
            } else {
                this.showNotification('分析失败', 'error');
            }
        } catch (error) {
            console.error('分析问题出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 显示分析结果
     */
    showAnalysisResult(analysis) {
        const modalHtml = `
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="analysisResultModal">
                <div class="bg-white rounded-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">分析结果</h3>
                        <button class="text-gray-500 hover:text-gray-700" onclick="keyIssuesManager.closeModal('analysisResultModal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">问题根因</label>
                            <p class="text-sm text-gray-900">${analysis.root_cause}</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">影响范围</label>
                            <p class="text-sm text-gray-900">${analysis.impact_scope}</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">解决方案</label>
                            <p class="text-sm text-gray-900">${analysis.solution}</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">预防措施</label>
                            <p class="text-sm text-gray-900">${analysis.prevention}</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">责任部门</label>
                            <p class="text-sm text-gray-900">${analysis.responsible_department}</p>
                        </div>
                    </div>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
    }

    /**
     * 批量分析问题
     */
    async batchAnalyzeIssues() {
        if (this.selectedIssues.size === 0) {
            this.showNotification('请选择要分析的问题', 'warning');
            return;
        }

        try {
            const response = await fetch('/api/key-issues/batch-analyze', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    issue_ids: Array.from(this.selectedIssues)
                })
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('批量分析任务已提交', 'success');
                this.selectedIssues.clear();
                this.renderIssuesList();
            } else {
                this.showNotification('批量分析失败', 'error');
            }
        } catch (error) {
            console.error('批量分析出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 批量导出问题
     */
    batchExportIssues() {
        if (this.selectedIssues.size === 0) {
            this.showNotification('请选择要导出的问题', 'warning');
            return;
        }

        const selectedData = this.issues.filter(issue => 
            this.selectedIssues.has(issue.id)
        );

        this.exportToExcel(selectedData, 'selected_issues.xlsx');
    }

    /**
     * 导出重点问题
     */
    exportKeyIssues() {
        this.exportToExcel(this.issues, 'key_issues.xlsx');
    }

    /**
     * 导出为Excel
     */
    exportToExcel(data, filename) {
        // 简单的CSV导出实现
        const headers = ['问题编号', '问题描述', '涉及区域', '发生频次', '严重程度', '处理状态'];
        const csvContent = [
            headers.join(','),
            ...data.map(issue => [
                issue.issue_code,
                `"${issue.title}"`,
                `${issue.region} - ${issue.district}`,
                issue.frequency,
                issue.severity,
                issue.status
            ].join(','))
        ].join('\n');

        const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        link.click();

        this.showNotification('导出成功', 'success');
    }

    /**
     * 关闭模态框
     */
    closeModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.remove();
        }
    }

    /**
     * 显示通知
     */
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        const colors = {
            success: 'bg-green-500',
            error: 'bg-red-500',
            warning: 'bg-yellow-500',
            info: 'bg-blue-500'
        };

        notification.className = `fixed top-4 right-4 ${colors[type]} text-white px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full`;
        notification.textContent = message;

        document.body.appendChild(notification);

        setTimeout(() => {
            notification.classList.remove('translate-x-full');
        }, 100);

        setTimeout(() => {
            notification.classList.add('translate-x-full');
            setTimeout(() => {
                notification.remove();
            }, 300);
        }, 3000);
    }

    /**
     * 销毁实例
     */
    destroy() {
        // 销毁图表
        Object.keys(this.charts).forEach(key => {
            if (this.charts[key]) {
                this.charts[key].destroy();
            }
        });
    }
}

// 页面加载完成后初始化重点问题分析管理器
document.addEventListener('DOMContentLoaded', function() {
    window.keyIssuesManager = new KeyIssuesManager();
});

// 监听页面卸载事件
window.addEventListener('beforeunload', function() {
    if (window.keyIssuesManager) {
        window.keyIssuesManager.destroy();
    }
});